package com.xyz.aop;

import cn.hutool.core.util.StrUtil;
import com.xyz.entity.mapper.SystemUrlLogMapper;
import com.xyz.entity.pojo.SystemUrlLog;
import com.xyz.util.RedisUtil;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.LoginInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 系统日志处理
 */
@Component // 声明这是一个组件
@Aspect // 声明这是一个切面Bean
@Order(3) // 优先级
public class SystemLogAspect {

    @Autowired
    private SystemUrlLogMapper systemUrlLogMapper;

    @Autowired
    private RedisUtil redis;

    // 配置环绕通知
    @Around("execution(* com.xyz.controller..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取request response对象
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String url = request.getRequestURI();
        // 排除不用登陆的接口
        if (LoginAspect.urlList.contains(url) || request.getRequestURI().contains("/system/readFile/") || request.getRequestURI().contains("/message/connect")) {
            return joinPoint.proceed();
        }
        Date requestDate = new Date();
        DataResult dataResult = (DataResult) joinPoint.proceed();
        Date responseDate = new Date();

        Object[] args = joinPoint.getArgs();
        if (dataResult != null && args.length != 0 && args[0] != null) {
            LoginInfo li = (LoginInfo) args[0];
            SystemUrlLog sul = new SystemUrlLog();
            sul.setUserId(li.getLoginUserId());
            sul.setUsername(li.getLoginUsername());
            sul.setIp(StrUtil.isNotBlank(request.getRemoteAddr()) ? request.getRemoteAddr() : "未知");
            sul.setUrl(url);
            sul.setRequestTime(requestDate);
            sul.setRequestResult(dataResult.toInfo());
            sul.setResponseTime(responseDate);
            systemUrlLogMapper.insert(sul);
        }

        return dataResult;
    }

}
